//
//  SearchTableViewController.m
//  ksjv2
//
//  Created by mac on 15/1/7.
//  Copyright (c) 2015年 CnbizMedia. All rights reserved.
//

#import "SearchTableViewController.h"
#import "Util.h"
#import "ArticleViewController.h"
@interface SearchTableViewController ()<UITableViewDataSource,UITableViewDelegate>{
    NSMutableArray *searchResult;
    NSString*key;
    long int _page;
    UIButton*button;
}

@end

@implementation SearchTableViewController

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    key=searchBar.text;
    self.searchDisplayController.searchResultsTableView.hidden = YES;
    
    [self loadNews];
    
    [self resignFirst];
   
}
-(void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
    [self resignFirst];
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
    searchBar.text=@"";
    if (_page!=1&&searchResult.count!=0) {
        _page=1;
        [searchResult removeAllObjects];
        [self.TableView reloadData];
    }
    [UIView animateWithDuration:.2 animations:^{
        button.alpha=1;
    }];
    
//    [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:NO];
//    [self.navigationController setNavigationBarHidden:YES animated:YES];
    
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self resignFirst];
}
-(void)resignFirst{
    [UIView animateWithDuration:.2 animations:^{
        button.alpha=0;
    }];
//    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:NO];
//    [self.navigationController setNavigationBarHidden:NO animated:YES];
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
}



-(void)loadNews{
    NSMutableDictionary*parameter;
    [SVProgressHUD show];
//    if (_page==1) {
        parameter=[@{@"p":[NSString stringWithFormat:@"%ld",_page],@"k":key} mutableCopy];
//    }else{
//        parameter=[@{@"p":[NSString stringWithFormat:@"%ld",_page],@"k":key} mutableCopy];
//    }
    [[AppAPIClient sharedClient] GET:@"Search/News" parameters:parameter success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [SVProgressHUD dismiss];
        NSMutableDictionary *result = responseObject[@"data"];
        if([result isKindOfClass:[NSNull class]] || [result count] == 0){
            return;
        }
        if(searchResult == nil){
            searchResult = [[NSMutableArray alloc]initWithArray:responseObject[@"data"] copyItems:YES];
        }else{
            NSMutableArray *newResult = [[NSMutableArray alloc]initWithArray:searchResult];
            [newResult addObjectsFromArray:responseObject[@"data"]];
            searchResult = [[NSMutableArray alloc]initWithArray:newResult copyItems:YES];
        }
        _page++;
        [self.TableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",operation.responseString);
    }];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    _page=1;
    self.title=@"搜索";

    button=[UIButton buttonWithType:UIButtonTypeCustom];
    [button setFrame:CGRectMake(0, 44, self.view.frame.size.width, self.view.frame.size.height)];
    [button setAlpha:0];
    [button setBackgroundColor:[UIColor colorWithWhite:0.000 alpha:0.250]];
    [button addTarget:self action:@selector(resignFirst) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    self.TableView.tableFooterView=[[UIView alloc]initWithFrame:CGRectZero];
    self.TableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    
    UIButton *buttonf=[UIButton buttonWithType:UIButtonTypeCustom];
    [buttonf setFrame:CGRectMake(0, 0, 22, 22)];
    [buttonf addTarget:self action:@selector(popOfDismss) forControlEvents:UIControlEventTouchUpInside];
    [buttonf setImage:[UIImage imageNamed:@"dismiss"] forState:UIControlStateNormal];
     UIBarButtonItem*leftBarItem = [[UIBarButtonItem alloc]initWithCustomView:buttonf];
    self.navigationItem.leftBarButtonItem=leftBarItem;
    ////添加返回手势
    UISwipeGestureRecognizer *recognizer = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(handleSwipeFrom:)];
    [recognizer setDirection:(UISwipeGestureRecognizerDirectionRight)];
    [[self view] addGestureRecognizer:recognizer];
    
    
}
-(void)viewDidLayoutSubviews{
//    [self.tableView.tableHeaderView setFrame:CGRectMake(0, 60, self.tableView.tableHeaderView.frame.size.width, self.tableView.tableHeaderView.frame.size.height)];
//    [[self.tableView superview] addSubview:self.tableView.tableHeaderView];
//    [self.tableView setFrame:CGRectMake(0, self.tableView.tableHeaderView.frame.origin.y+self.tableView.tableHeaderView.frame.size.height, self.tableView.frame.size.width, self.tableView.frame.size.height)];
}
-(void)handleSwipeFrom:(UISwipeGestureRecognizer *)recognizer{
    
    if(recognizer.direction==UISwipeGestureRecognizerDirectionRight) {
        CATransition*transition=[CATransition animation];
        transition.duration=1;
        transition.timingFunction=[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
        transition.type=kCATransitionPush;
        transition.subtype=kCATransitionFromLeft;//方向
        [self.view.layer addAnimation:transition forKey:nil];
        [self popOfDismss];
        //        [self dismissViewControllerAnimated:YES completion:^{
        [SVProgressHUD dismiss];
        //        }];
        
    }
}
-(void)popOfDismss{
    if ([[self.navigationController viewControllers] count]>=2) {
        [self.navigationController popViewControllerAnimated:YES];
        
    }else{
        
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return [searchResult count];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    int type =0;
    //    type = [[_userData[indexPath.row] objectForKey:@"type"] intValue];
    if ([[searchResult[indexPath.row] objectForKey:@"thumb"] length]>6) {
        type = 2;
    }else{
        type = 1;
    }
    
    if (type==1) {
        return 65;
    }else if (type==2) {
        return 115;
    }else{
        return 0;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell * cell;
    if(indexPath.row == [searchResult count]-1){
        [self loadNews];
    }
    long int type =0;
    //    type = [[_userData[indexPath.row] objectForKey:@"type"] intValue];
    if ([[searchResult[indexPath.row] objectForKey:@"thumb"] length]>6) {
        type = 2;
    }else{
        type = 1;
    }
    
    
    if (type==1) {
        cell= [tableView dequeueReusableCellWithIdentifier:@"cell1" forIndexPath:indexPath];
        if (cell==nil) {
            cell=[tableView dequeueReusableCellWithIdentifier:@"cell1"];
        }
    }else if (type==2) {
        cell= [tableView dequeueReusableCellWithIdentifier:@"cell2" forIndexPath:indexPath];
        if (cell==nil) {
            cell=[tableView dequeueReusableCellWithIdentifier:@"cell2"];
        }
    }
    cell.backgroundColor=UIColorFromRGB(0xf5f5f5);
    if (type==1) {
        return [self LoadDataType1:tableView Cell:cell IndexPath:indexPath];
    }else if (type==2) {
        return [self LoadDataType2:tableView Cell:cell IndexPath:indexPath];
    }else{
        return cell;
    }


}
-(UITableViewCell *)LoadDataType1:(UITableView*)tableView Cell:(UITableViewCell*)cell IndexPath:(NSIndexPath *)indexPath {
    //    NSLog(@"row---%d",indexPath.row);
    UILabel*label1=(UILabel*)[cell.contentView viewWithTag:11];
    label1.text=[NSString stringWithFormat:@"%@",searchResult[indexPath.row][@"title"]];
    
    UILabel*label2=(UILabel*)[cell.contentView viewWithTag:22];
    NSDate * dt = [NSDate dateWithTimeIntervalSince1970:[searchResult[indexPath.row][@"inputtime"] floatValue]];
    NSDateFormatter * df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyy-MM-dd mm:ss"];
    NSString *regStr = [df stringFromDate:dt];
    label2.text=[NSString stringWithFormat:@"%@",regStr];
    
    
    UILabel*label3=(UILabel*)[cell.contentView viewWithTag:33];
    label3.text=[NSString stringWithFormat:@"%@",searchResult[indexPath.row][@"comment"]];
    
    return cell;
}
-(UITableViewCell *)LoadDataType2:(UITableView*)tableView Cell:(UITableViewCell*)cell IndexPath:(NSIndexPath *)indexPath {
    
    UILabel*label1=(UILabel*)[cell.contentView viewWithTag:11];
    label1.text=[NSString stringWithFormat:@"%@",searchResult[indexPath.row][@"title"]];
    
    UILabel*label2=(UILabel*)[cell.contentView viewWithTag:22];
    NSDate * dt = [NSDate dateWithTimeIntervalSince1970:[searchResult[indexPath.row][@"inputtime"] floatValue]];
    NSDateFormatter * df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyy-MM-dd mm:ss"];
    NSString *regStr = [df stringFromDate:dt];
    label2.text=[NSString stringWithFormat:@"%@",regStr];
    
    UILabel*label3=(UILabel*)[cell.contentView viewWithTag:33];
    label3.text=[NSString stringWithFormat:@"%@",searchResult[indexPath.row][@"comment"]];
    
    UIImageView*imageview=(UIImageView*)[cell.contentView viewWithTag:44];
    [imageview sd_setImageWithURL:[NSURL URLWithString:searchResult[indexPath.row][@"thumb"]] placeholderImage:[UIImage imageNamed:@"placeholderImage"] ];
    
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:NO];//点击后不会有阴影
    UIStoryboard*story=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
    ArticleViewController*art=[story instantiateViewControllerWithIdentifier:@"ArticleViewController"];
    art._Dict=searchResult[indexPath.row];
    art.isCommentVC=NO;
    art.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentViewController:art animated:YES completion:nil];
    
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
